<!--
 * @页面名称:目录检索
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card catalogSearch">
    <div class="com-top"></div>
    <div class="com-content">
      <splitpanes :dbl-click-splitter="false" horizontal style="height: 100%">
        <pane>
          <stable
            style="height: 100%"
            :columns="showType === 'folder' ? tableSetting.columns : tableSetting.columns2"
            :data="tableSetting.data"
            :tablePage="tableSetting.tablePage"
            :pageSizes="[15, 100, 1000, { label: '全量数据', value: -1 }]"
            :toolbarConfigVisible="true"
            :proxyConfig="tableSetting.proxyConfig"
            @rowClick="rowClick"
            @pageChange="pageChange"
            @selectionChange="tableSelect"
          >
            <template #toolbarButtons>
              <div>
                <el-row type="flex" justify="start" align="middle">
                  <el-col :span="24" style="display: flex; gap: 8px">
                    <div class="query">
                      <el-tree-select
                        check-strictly
                        v-model="Fonds_ID"
                        @change="onFondsChange"
                        node-key="Fonds_ID"
                        placeholder="请选择全宗"
                        :props="{ label: 'Fonds_Name', children: 'children' }"
                        :data="FondsData"
                        :render-after-expand="false"
                      />
                    </div>
                    <div class="query">
                      <el-select v-model="FMT_ID" @change="onFMTChange" placeholder="请选择归档方式">
                        <el-option v-for="item in FMTOption" :key="item.FMT_ID" :label="item.FM_OCName" :value="item.FMT_ID" />
                      </el-select>
                    </div>
                    <div class="query">
                      <el-tree-select
                        class="CatalogSelect"
                        check-strictly
                        v-model="Catalog_ID"
                        :data="catalogList"
                        placeholder="请选择分类"
                        node-key="Catalog_ID"
                        :props="{ label: 'Catalog_Name', children: 'children' }"
                        :render-after-expand="false"
                      />
                    </div>
                    <div class="query">
                      <el-input v-model="searchString">
                        <template #prepend>
                          <el-select v-model="showType" style="width: 115px" @change="onChange">
                            <el-option :label="item.name" :value="item.type" v-for="item in searchSelect" :key="item.type" />
                          </el-select>
                        </template>
                        <template #append>
                          <el-button type="primary" icon="Search" @click="onSearch">搜索</el-button>
                        </template>
                      </el-input>
                    </div>
                    <div class="query">
                      <el-dropdown @command="handleExportClick">
                        <el-button type="primary" style="margin-left: 8px; vertical-align: center"
                          >导出数据 <el-icon class="el-icon--right"><arrow-down /></el-icon
                        ></el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="1">导出案卷数据</el-dropdown-item>
                            <el-dropdown-item command="2">导出文件数据</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
          </stable>
        </pane>
        <pane>
          <div style="height: 100%" v-if="showType === 'folder'">
            <splitpanes :dbl-click-splitter="false" style="height: 100%">
              <pane>
                <!-- 副表格 -->
                <Stable :columns="tableSetting2.columns" :data="tableSetting2.data" @rowClick="rowClick2"></Stable>
              </pane>
              <pane>
                <!-- 全文表格 -->
                <Stable
                  :columns="tableSetting3.columns"
                  :data="tableSetting3.data"
                  :tableMenu="tableSetting3.tableMenu"
                  @rowdblClick="rowdblClick"
                  @menuClick="menuClick"
                ></Stable>
              </pane>
            </splitpanes>
          </div>
          <div style="height: 100%" v-else>
            <!-- 全文表格 -->
            <Stable
              :columns="tableSetting3.columns"
              :data="tableSetting3.data"
              :tableMenu="tableSetting3.tableMenu"
              @rowdblClick="rowdblClick"
              @menuClick="menuClick"
            ></Stable>
          </div>
        </pane>
      </splitpanes>
    </div>
    <!-- 全文预览 -->
    <preview
      v-if="fulltextConfig.visible"
      :visible="fulltextConfig.visible"
      :type="fulltextConfig.type"
      :fileList="fulltextConfig.fileList"
      :download="fulltextConfig.download"
      :print="fulltextConfig.print"
      @updataVisible="updataVisible"
    ></preview>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
// import { formatter } from "./formatter";
import { transTree } from "@/utils/util";
import { useAppStore } from "@/stores/modules/app";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import { previewFulltext } from "@/components/Preview/ts/index";
import Preview from "@/components/Preview/Preview.vue";
import { fileSizeFormat } from "@/utils/formatter";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import dtime from "moment";
import ACrypto from "@/utils/crypto";

const { proxy } = useCurrentInstance();
// 获取pinia数据
const appStore = useAppStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
// 全宗绑定字段
const Fonds_ID = ref("");
// 全宗数据集合
const FondsData: any = ref([]);
// 归档方式绑定数据
const FMT_ID = ref("");
// 归档方式数据集合
const FMTOption: any = ref([]);
// 当前点击的归档方式数据
const currClass: any = ref({});
// 分类绑定字段
const Catalog_ID = ref("");
// 分类数据集合
const catalogList: any = ref([]);
// 搜索绑定字段
const searchString = ref("");
// 文件类型绑定字段
const showType = ref("folder");
// 输入选择框数据集合
const searchSelect = ref([
  { type: "folder", name: "案卷查询" },
  { type: "file", name: "文件查询" }
]);
// 全文预览配置参数
const fulltextConfig = reactive({
  // 预览全文配置参数
  visible: false,
  fileList: [] as any[],
  type: "",
  download: false,
  print: false
});
const formatter = ({ row, column, cellValue }: any) => {
  const catalogList = catalogStore.catalogList;
  // 保管期限
  if (column.property === "BGQXdata") {
    const BGQX = dictionryStore.getDictionaryObj["BGQXdata"];
    const data = BGQX.find((v: any) => v.DDL_ID === cellValue);
    return data ? data.DDL_Value : "";
  }
  // 分类
  if (column.property === "Catalog_ID") {
    const data = catalogList.find((v: any) => v.Catalog_ID === cellValue);
    console.log(catalogList, cellValue);
    return data ? data.Catalog_Name : "";
  }
  if (column.property === "ResponsiblePerson") {
    // 责任者
    const result = dictionryStore.getDictionaryObj["ResponsiblePerson"];
    const data = result.find((v: any) => v.DDL_ID === cellValue);
    return data ? data.DDL_Value : cellValue;
  }
  if (column.property === "Filing_Time") {
    // 归档日期
    return cellValue ? dtime(cellValue).format("YYYY-MM-DD") : "";
  }
  if (column.property === "Title") {
    cellValue = ACrypto.getSS(row[column.property]);
  }
  return cellValue;
};
// 主表格设置
const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 60 },
    { title: "序号", type: "seq", width: 50, sortable: true },
    { title: "分类号", field: "Catalog_ID", width: 180, sortable: true, formatter: formatter },
    { title: "年代号", field: "Year", width: 100, sortable: true },
    { title: "档号", field: "Code", width: 180, sortable: true },
    {
      title: "案卷题名",
      field: "Title",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<span v-html={showData(row.Title)}></span>];
        }
      }
    },
    { title: "总页数", field: "PageCount", width: 120, sortable: true },
    { title: "保管期限", field: "BGQXdata", sortable: true, width: 150, formatter: formatter }
  ],
  columns2: [
    // 副表格表头数据
    { type: "checkbox", width: 60 },
    { title: "序号", type: "seq", width: 60, sortable: true },
    { title: "分类号", field: "Catalog_ID", width: 150, sortable: true, formatter: formatter },
    { title: "年代号", field: "Year", width: 100, sortable: true },
    { title: "档号", field: "Code", width: 120, sortable: true },
    { title: "文件编号", field: "FileSerial", width: 120, sortable: true },
    { title: "责任者", field: "ResponsiblePerson", width: 120, sortable: true, formatter: formatter },
    {
      title: "文件题名",
      field: "Title",
      minWidth: 150,
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<span v-html={showData(row.Title)}></span>];
        }
      },
      formatter: formatter
    },
    { title: "日期", field: "Filing_Time", width: 150, sortable: true },
    { title: "页数", field: "PageCount", width: 120, sortable: true },
    { title: "备注", field: "Remark", width: 120, sortable: true }
  ],
  data: [],
  tablePage: {
    showPage: true,
    pageIndex: 1,
    pageSize: 15,
    total: 0
  },
  rowClickObject: {},
  proxyConfig: {
    autoLoad: false,
    response: {
      result: "result",
      total: "page.total"
    },
    ajax: {
      // 接收 Promise
      query: (res: any) => {
        console.log(res);

        return onRefresh();
      }
    }
  }
});
// 卷内/文件表格设置
const tableSetting2 = reactive({
  columns: [
    // 副表格表头数据
    { title: "序号", type: "seq", width: 60, sortable: true },
    { title: "分类号", field: "Catalog_ID", width: 150, sortable: true, formatter: formatter },
    { title: "年代号", field: "Year", width: 100, sortable: true },
    { title: "档号", field: "Code", width: 120, sortable: true },
    { title: "文件编号", field: "FileNumber", width: 120, sortable: true },
    { title: "责任者", field: "Responsibility", width: 120, sortable: true, formatter: formatter },
    { title: "文件题名", field: "Title", minWidth: 150, sortable: true, formatter: formatter },
    { title: "日期", field: "Filing_Time", width: 150, sortable: true },
    { title: "页数", field: "PageCount", width: 120, sortable: true },
    { title: "备注", field: "Remark", width: 120, sortable: true }
  ],
  data: []
});
// 全文表格设置
const tableSetting3 = reactive({
  columns: [
    { title: "顺序号", field: "AI_Index", sortable: true },
    { title: "文件名", field: "AI_Name", sortable: true },
    { title: "文件大小", field: "AI_Source_Size", sortable: true, formatter: fileSizeFormat },
    { title: "上传时间", field: "AI_UploadDateTime", sortable: true },
    { title: "创建时间", field: "AI_FileDateTime", sortable: true }
  ],
  data: [],
  tableMenu: {
    enabled: true,
    className: "my-menus",
    body: {
      options: [[{ code: "dataInfo", name: "加入超链接清单", prefixIcon: "DocumentAdd", className: "my-copy-item" }]]
    }
  }
});
// 表格勾选事件
const fileSelect = ref([]);
// 搜索条件切换
const onChange = (val: string) => {
  showType.value = val;
  if (val === "folder") {
    // 表格置空操作
    tableSetting.data = [];
    tableSetting2.data = [];
    tableSetting3.data = [];
  } else {
    // 表格置空操作
    tableSetting.data = [];
    tableSetting2.data = [];
    tableSetting3.data = [];
  }
};
// 获取全宗数据
const getFondsData = () => {
  proxy.$vueAxios.get("Master_Base_Fonds/Get", { order: "Fonds_Order asc" }).then((res: any) => {
    FondsData.value = transTree(res.List, "Fonds_ID", "Fonds_Father");
  });
};
// 切换全宗事件
const onFondsChange = (val: any) => {
  FMT_ID.value = "";
  Catalog_ID.value = "";
  proxy.$vueAxios.get("DynamicStatistics/GetFM", { fondsID: val }, { noLoading: true }).then((res: any) => {
    console.log(res.List);

    FMTOption.value = res.List.sort((a: any, b: any) => a.Class_Order - b.Class_Order);
  });
};
// 切换归档方式事件
const onFMTChange = (val: any) => {
  currClass.value = FMTOption.value.find((v: any) => v.FMT_ID === val);
  // 置空分类选择
  Catalog_ID.value = "";
  // 获取分类数据
  proxy.$vueAxios.get("Dynamicstatistics/GetCatalog", { fmid: currClass.value.FM_ID }).then((res: any) => {
    catalogList.value = transTree(res.List, "Catalog_ID", "Catalog_Father");
  });
  if ([2].includes(currClass.value.FMT_Type)) {
    showType.value = "file";
    searchSelect.value = [{ type: "file", name: "文件查询" }];
  } else {
    showType.value = "folder";
    searchSelect.value = [
      { type: "folder", name: "案卷查询" },
      { type: "file", name: "文件查询" }
    ];
  }
};
// 搜索事件
const onSearch = () => {
  tableSetting2.data = [];
  tableSetting3.data = [];
  tableSetting.tablePage.pageIndex = 1;
  // 根据关键字搜索表格内容
  getTableData();
};
// 获取主表格数据
const getTableData = () => {
  if (!FMT_ID.value) {
    proxy.$message.warning("请选择归档方式!");
    return;
  }
  const { LoadingConfig } = appStore;
  LoadingConfig.contentLoading = true;
  if (showType.value === "folder") {
    // 案卷级查询
    proxy.$vueAxios
      .get(
        "SearchContent/getRoll",
        {
          keywords: searchString.value,
          fmtId: currClass.value.FMT_ID,
          catalogid: Catalog_ID.value,
          pageIndex: tableSetting.tablePage.pageIndex,
          pageSize: tableSetting.tablePage.pageSize
        },
        { noLoading: true }
      )
      .then((res: any) => {
        if (res.Mark) {
          LoadingConfig.contentLoading = false;
          tableSetting.tablePage.total = res.Count;
          tableSetting.data = res.List;
        } else {
          LoadingConfig.contentLoading = false;
          proxy.$message.error(res.Msg);
        }
      })
      .catch((err: any) => {
        proxy.$message.error(err);
        LoadingConfig.contentLoading = false;
      });
  } else {
    // 文件级查询
    proxy.$vueAxios
      .get(
        "SearchContent/getFile",
        {
          keywords: searchString.value,
          fmtId: currClass.value.FMT_Type === 1 ? currClass.value.JNFMT_ID : currClass.value.FMT_ID,
          catalogid: Catalog_ID.value,
          pageIndex: tableSetting.tablePage.pageIndex,
          pageSize: tableSetting.tablePage.pageSize
        },
        { noLoading: true }
      )
      .then((res: any) => {
        if (res.Mark) {
          LoadingConfig.contentLoading = false;
          tableSetting.tablePage.total = res.Count;
          tableSetting.data = res.List;
        } else {
          LoadingConfig.contentLoading = false;
          proxy.$message.error(res.Msg);
        }
      })
      .catch((err: any) => {
        proxy.$message.error(err);
        LoadingConfig.contentLoading = false;
      });
  }
};
// 工具栏刷新
const onRefresh = () => {
  return new Promise(resolve => {
    if (!FMT_ID.value) {
      proxy.$message.warning("请选择归档方式!");
      return;
    }
    const { LoadingConfig } = appStore;
    LoadingConfig.contentLoading = true;
    if (showType.value === "folder") {
      // 案卷级查询
      proxy.$vueAxios
        .get(
          "SearchContent/getRoll",
          {
            keywords: searchString.value,
            fmtId: currClass.value.FMT_ID,
            catalogid: Catalog_ID.value,
            pageIndex: tableSetting.tablePage.pageIndex,
            pageSize: tableSetting.tablePage.pageSize
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            LoadingConfig.contentLoading = false;
            // resolve(res);
            resolve({
              page: {
                total: res.Count
              },
              result: res.List
            });
          } else {
            LoadingConfig.contentLoading = false;
            proxy.$message.error(res.Msg);
          }
        })
        .catch((err: any) => {
          proxy.$message.error(err);
          LoadingConfig.contentLoading = false;
        });
    } else {
      // 文件级查询
      proxy.$vueAxios
        .get(
          "SearchContent/getFile",
          {
            keywords: searchString.value,
            fmtId: currClass.value.FMT_Type === 1 ? currClass.value.JNFMT_ID : currClass.value.FMT_ID,
            catalogid: Catalog_ID.value,
            pageIndex: tableSetting.tablePage.pageIndex,
            pageSize: tableSetting.tablePage.pageSize
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            LoadingConfig.contentLoading = false;
            resolve(res);
          } else {
            LoadingConfig.contentLoading = false;
            proxy.$message.error(res.Msg);
          }
        })
        .catch((err: any) => {
          proxy.$message.error(err);
          LoadingConfig.contentLoading = false;
        });
    }
  });
};
// 切换分页
const pageChange = ({ pageIndex, pageSize }: any) => {
  tableSetting.tablePage.pageIndex = pageIndex;
  tableSetting.tablePage.pageSize = pageSize;
  getTableData();
};
// 主表格单击事件
const rowClick = ({ row }: any) => {
  tableSetting.rowClickObject = row;
  // 获取全文数据
  getFullData({ table_id: row.Record_ID });
  // 查询卷内数据
  if (showType.value === "folder") {
    proxy.$vueAxios
      .get("SearchContent/getRollWithin", { id: row.Record_ID, fmid: row.FM_ID, catalogid: row.Catalog_ID })
      .then((res: any) => {
        tableSetting2.data = res.List; // 赋值副表数据
      });
  }
};
// 主表勾选事件
const tableSelect = (val: any) => {
  fileSelect.value = val;
};
// 卷内/文件表格单击事件
const rowClick2 = ({ row }: any) => {
  getFullData({ table_id: row.Record_ID });
};
// 全文表格双击事件
const rowdblClick = ({ row }: any) => {
  previewFulltext(
    {
      id: row.AI_ID,
      fulltextRow: row,
      fulltextTableData: tableSetting3.data,
      config: fulltextConfig,
      IsAllow: true
    },
    proxy
  );
};
// 获取全文数据
const getFullData = (param: any) => {
  proxy.$vueAxios
    .post("Master_Base_AllInfos/GetConditional", {
      order: "AI_Index asc",
      dtoList: [{ fieldName: "Record_ID", fieldValue: param.table_id }]
    })
    .then((res: any) => {
      tableSetting3.data = res.List;
    });
};
// 搜索数据显示高亮
const showData = (val: string) => {
  const newVal = ACrypto.getSS(val);
  if (newVal?.indexOf(searchString.value) !== -1 && searchString.value !== "" && newVal) {
    return newVal.replace(searchString.value, '<font color="red">' + searchString.value + "</font>");
  } else {
    return newVal;
  }
};
// 更新预览窗口状态
const updataVisible = (value: boolean) => {
  fulltextConfig.visible = value;
};
// 报表导出点击事件
const handleExportClick = (command: string | number | object) => {
  if (fileSelect.value.length === 0) {
    proxy.$message.warning("未选中任何数据!");
    return;
  }
  switch (command) {
    case "1":
      proxy.$vueAxios.post("Excel/ImportCatalogSearchFiles", { list: fileSelect.value }, "导出数据(案卷).xlsx");
      break;
    case "2":
      proxy.$vueAxios.post("Excel/ImportCatalogSearchFile", { list: fileSelect.value }, "导出数据(文件).xlsx");
      break;
    default:
      break;
  }
};
// 右键点击
const menuClick = ({ menu, row, column }: any) => {
  if (!row) {
    proxy.$message.warning("请选中数据!");
    return;
  }
  if (menu.code === "dataInfo") {
    const id = proxy.$global.createID();
    proxy.$vueAxios
      .post("MasterBaseBorrow/Add", {
        id: id,
        fM_ID: row.FM_ID,
        fmT_ID: row.FMT_ID,
        status: row.Status,
        record_ID: row.Record_ID,
        stdaList: [{ id: proxy.$global.createID(), stD_ID: id }]
      })
      .then((res: any) => {
        if (res.Mark) {
          proxy.$message.success("添加成功!");
          proxy.$vueAxios.get("MasterBaseBorrow/Get").then((res: any) => {
            if (res.Mark) {
              userStore.setFileCount(res.Count);
            }
          });
        }
      });
  }
};
onMounted(() => {
  getFondsData();
});
watch(
  () => showType.value,
  (newVal, oldVal) => {
    if (newVal === "folder") {
      // 表格置空操作
      tableSetting.data = [];
      tableSetting2.data = [];
      tableSetting3.data = [];
    } else {
      // 表格置空操作
      tableSetting.data = [];
      tableSetting2.data = [];
      tableSetting3.data = [];
    }
  }
);
</script>

<style scoped lang="scss">
.catalogSearch {
  height: 100%;
  .com-top {
    margin-bottom: 5px;
    .query {
      display: flex;
      align-items: center;
      padding-right: 10px;

      // width: 400px;
    }
    .top-icon {
      display: flex;
      align-items: center;
      .img {
        width: 35px;
        height: 35px;
        font-size: 20px;
        line-height: 35px;
        color: #ffffff;
      }
    }
  }
  .com-content {
    height: calc(100% - 5px);
    .pagination {
      height: 30px;
      text-align: right;
    }
  }
}
</style>
